package com.sport.config.security.service;

import com.sport.entity.SysMenu;
import com.sport.entity.SysUser;
import com.sport.mapper.SysUserMapper;
import com.sport.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class userDetailServiceImpl implements UserDetailsService {
    @Autowired
    SysUserMapper sysUserMapper;


    @Autowired
    RedisUtil redisUtil;

    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//        在mapper自定义登录，根据用户名获取用户信息
         SysUser user;
         if(redisUtil.hasKey("userInfo_"+username)){
//             缓存中存在用户信息，直接从redis中去，
             System.out.println("在redis上面去");
             user=(SysUser)redisUtil.getObject("userInfo_"+username);
         }else{
             user=sysUserMapper.findByUsername(username);
         }

        if(null==user){
            throw new UsernameNotFoundException("用户名或者密码错误");
        }
        System.out.println("根据用户名查询信息的方法"+user);
         if (user.getUsername().equals("admin")){
             System.out.println("进入查询阶段");
//             List<SysRole> list=new ArrayList<>();
//             SysRole role=new SysRole();
//             role.setCode("admin");
//             list.add(role);
//             user.setRoles(list);
//            user.setMenus(sysUserMapper.findMenus(null));
//             管理员需要查询角色信息
             user.setRoles(sysUserMapper.findRoles(null));
             user.setPermissions(sysUserMapper.findPermissions(null));
//             获取父级菜单
             List<SysMenu> menus =sysUserMapper.findMenus(null);
//             获取子级菜单
             menus.forEach(item->item.setChildren((sysUserMapper.findChildrenMenu(item.getId(),null))));
             user.setMenus(menus);
             }

         else {
             //非管理员需要查询角色信息
        user.setRoles(sysUserMapper.findRoles(user.getId()));
        user.setPermissions(sysUserMapper.findPermissions(user.getId()));
//        获取父级菜单
             List<SysMenu> menus=sysUserMapper.userfindMenus();
             menus.forEach(item->item.setChildren(sysUserMapper.findChildrenMenu(item.getId(),user.getId())));
//             menus.forEach(item->item.setChildren(sysUserMapper.userfindMenus()));
             user.setMenus(menus);
         }
         user.setPassword(null);
            redisUtil.setValue("userInfo_"+username,user);
         return user;
    }

}
